# import socket
# import time
#
# def main():
#     udp_addr = ('192.168.228.128',9999)  #ip地址与端口号
#     udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#建立 udpsocket
#
#     for i in range(5):
#         data = "hello, this is the{} times messages!".format(i)
#         data = data.encode("utf-8") #数据编码
#         udp_socket.sendto(data,udp_addr)#传输数据
#         print("send {} times messages".format(i))
#
#         recv_data,addr = udp_socket.recvfrom(1024)
#         print("[from{0}:{1}:{2}".format(addr[0], addr[1], recv_data.decode("utf-8")))
#
#         time.sleep(1)
#
#     udp_socket.close()  #关闭连接
#
# if __name__ == '__main__':
#     main()


#coding:utf-8
import pygame
import cv2
import threading
import socket

pygame.init()
def mythread(sock, data, addr):
    sock.sendto(data, addr)
    print("已发送" + str(len(data)) + " bytes")
    sock.close()

def main():
    print("begin")
    capture = cv2.VideoCapture(0)
    while True:
        ret, frame = capture.read()
        frame = cv2.flip(frame, -1) #图像翻转
        frame = cv2.resize(frame, (160, 120))

        cv2.imwrite("test.jpg", frame)

        Img = pygame.image.load('./test.jpg')

        string = pygame.image.tostring(Img, "RGB")

        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        t = threading.Thread(target=mythread, args=(sock, string, ('127.0.0.1', 9999)))
        t.start()
        if cv2.waitKey(10) & 0xff == ord('q'):
            break

if __name__ == '__main__':
    main()
    cv2.destroyAllWindows()